package com.henry.base.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Calculus implements Callable<Double> {
    private double beg;
    private double end;

    public Calculus(double beg, double end) {
        this.beg = beg;
        this.end = end;
    }

    @Override
    public Double call() throws Exception {
        return (1/beg+1/end)/2*(end-beg);
//        return null;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(20);
        List<Future<Double>> list = new ArrayList<>();
        double b=1;
        double e=100;
        double step = 0.001;
        double curr = b;
        long l = System.currentTimeMillis();
        while (curr<e) {
//            System.out.println("dasdad");
            double d = curr;
            curr=curr+step;
            if(curr>e)
                curr=e;
            Future<Double> future = pool.submit(new Calculus(d, curr));
            list.add(future);
        }
        double sum =0;
        for (Future<Double> future : list) {
            sum+=future.get();
        }
        System.out.println(sum);
        long l1 = System.currentTimeMillis();
        System.out.println("The whole process consumes "+(l1-l)+"ms");
        pool.shutdown();
    }
}
